package com.llcbenwu.social.qq.connect;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Template;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;

/**
 * @author lilinchun
 * @date 2021/11/2 0002 20:27
 */
@Slf4j
public class QQOAuth2Template  extends OAuth2Template {


    public QQOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String accessTokenUrl) {
        super(clientId, clientSecret, authorizeUrl, accessTokenUrl);
        //将这个参数设置为true时OAuth2Template中exchangeForAccess中才能带入client_id与client_secret
         setUseParametersForClientAuthentication(true);
    }

    @Override
    protected RestTemplate createRestTemplate() {
        RestTemplate restTemplate= super.createRestTemplate();
        //处理type为html的类型
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return restTemplate;
    }

    /**
     * 因为QQ互联返回的是一个json字符串而它自带的是返回一个map所以我们还需要重写postForAccessGrant
     * @param accessTokenUrl
     * @param parameters
     * @return
     */

    @Override
    protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
        log.info("accessTokenUrl:"+accessTokenUrl);
        log.info("parameters:"+parameters);
        String s=null;
        try {
             s = getRestTemplate().postForObject(accessTokenUrl, parameters, String.class);
        }catch (Exception e){
            log.info("即可在返回包中获取到Access Token错误："+e.getMessage());
        }

        log.info("获取accessToken的响应："+s);
        String[] items= StringUtils.splitByWholeSeparatorPreserveAllTokens(s,"&");
        String  accessToken=StringUtils.substringAfterLast(items[0],"=");
        Long expiresIn=new Long(StringUtils.substringAfterLast(items[1],"="));
        String refresToken=StringUtils.substringAfterLast(items[2],"=");
        return new AccessGrant(accessToken,null,refresToken,expiresIn);
    }
}
